import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        // 注意1：在客户端new一个Socket对象的时候，就连接服务器。
        // 注意2：Socket对象可以字节把点分十进制的serverIp转换成32位二进制数
        socket = new Socket(serverIp,serverPort);
    }

    public void start(){
        System.out.println("客户端启动!");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanner = new Scanner(System.in);
            while (true){
                // 1.客户端从控制台读取用户输入的内容
                System.out.print(">");
                String request = scanner.next();
                if (request.equals("exit")){
                    System.out.println("客户端关闭!");
                    break;
                }

                // 2.客户端把请求写入网卡，发送给服务器处理
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);   //注意：要写入"\n"
                printWriter.flush();  // 冲刷，保证数据写入网卡

                // 3.客户端读取服务器响应写回到网卡上的数据
                Scanner respScan = new Scanner(inputStream);
                String response = respScan.next();

                // 4.打印响应的结果
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
